<template>
  <!-- 编辑商品组件 -->
  <div class="edit-goods">
    <!-- 头部路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容区 -->
    <el-card class="box-card">
      <el-row>
        <el-alert
          :title="noticeConfig.text"
          :style="noticeConfig.style"
          show-icon
          :closable="false"
        >
        </el-alert>
      </el-row>
      <!-- 步骤条 -->
      <el-row style="margin-top: 15px">
        <el-steps
          :space="200"
          :active="setpsActive"
          finish-status="success"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-row>
      <!-- 各个内容面板 -->
      <el-row style="margin-top: 15px">
        <!-- 商品基本信息 -->
        <el-tabs
          :tab-position="'left'"
          style="height: 200px"
          :before-leave="switchTag"
          value="baseInfo"
        >
          <el-tab-pane label="基本信息" name="baseInfo">
            <el-form
              :model="editGoodsInfo"
              :rules="editGoodsInfo.baseInfoRules"
              ref="baseInfoForm"
              label-width="100px"
              label-position="top"
              class="demo-ruleForm"
              style="width: 100%"
            >
              <el-form-item label="商品名称：" prop="name">
                <el-input v-model.trim="editGoodsInfo.name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格：" prop="price">
                <el-input v-model.trim="editGoodsInfo.price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量：" prop="weight">
                <el-input v-model.trim="editGoodsInfo.weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量：" prop="num">
                <el-input v-model.number="editGoodsInfo.num"></el-input>
              </el-form-item>
              <el-form-item label="商品分类：" prop="category">
                <el-cascader
                  v-model="editGoodsInfo.category"
                  :options="editGoodsInfo.categoryList"
                  :props="editGoodsInfo.casProps"
                  ref="addCatCascader"
                  disabled
                  clearable
                  popper-class="cat-cascader"
                >
                </el-cascader>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="params">
            <div
              style="margin-top: 20px"
              v-for="item in editGoodsInfo.params"
              :key="item.attr_id"
            >
              <el-row v-if="item.attr_vals.length > 0">
                {{ item.attr_name }}
              </el-row>
              <el-row v-if="item.attr_vals.length > 0" style="margin-top: 20px">
                <el-checkbox
                  v-for="(item2, index) in item.attr_vals"
                  :key="index"
                  v-model="item2.bool"
                  :label="item2.value"
                  border
                  size="medium"
                ></el-checkbox>
              </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="attr">
            <el-form>
              <el-form-item
                :label="item.attr_name"
                v-for="item in editGoodsInfo.attrs"
                :key="item.attr_id"
              >
                <el-input v-model.trim="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="img">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="{ Authorization: token }"
              ref="upload"
              accept=".png,.jpg"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :auto-upload="true"
              :file-list="editGoodsInfo.pics"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="editGoodsInfo.dialogImageVisible">
              <img width="100%" :src="editGoodsInfo.dialogImageUrl" alt="" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="content">
            <vue-tinymce
              v-model="editGoodsInfo.content"
              :setting="tinymceConfig.setting"
            />
            <el-row style="margin-top: 20px">
              <el-button type="primary" @click="editGoodsSubmit()"
                >修改商品</el-button
              >
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>
  </div>
</template>

<script>
//价格验证
var checkPrice = (rule, value, callback) => {
  if (isNaN(value) || value <= 0) {
    callback(new Error("请输入正确的价格"));
  } else {
    callback();
  }
};

//商品重量验证
var checkWeight = (rule, value, callback) => {
  if (isNaN(value) || value < 0) {
    callback(new Error("请输入正确的重量"));
  } else {
    callback();
  }
};

//分类验证
var checkCategory = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请选择分类"));
  } else {
    if (value.length < 3) {
      callback(new Error("只能选择三级分类"));
    } else {
      callback();
    }
  }
};

//商品数量验证
var checkNum = (rule, value, callback) => {
  if (isNaN(value) || value <= 0 || parseInt(value) != value) {
    callback(new Error("请输入正确的数量"));
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      //token
      token: localStorage.getItem("token"),
      //头部消息提示条配置
      noticeConfig: {
        //文字
        text: "编辑商品信息",
        //样式
        style: {
          //字体颜色
          color: "#909399",
          //字体大小
          fontSize: "13px",
          //内容行高
          lineHeight: "21px",
          display: "flex",
          justifyContent: "center",
          //背景颜色
          backgroundColor: "#F4F4F5",
        },
      },
      //步骤条序号
      setpsActive: 0,
      //商品参数属性请求控制
      queryFlag: true,
      //加载层参数配置
      loadingConfig: {
        target: "body",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      },
      //编辑商品的ID
      editGoodsId: null,
      //编辑商品的基本信息
      editGoodsInfo: {
        //商品名称
        name: "",
        //商品价格
        price: 0,
        //商品数量
        num: 0,
        //商品重量
        weight: 0,
        //商品介绍
        content: "",
        pics: [],
        //参数列表
        params: [],
        //属性列表
        attrs: [],
        //所有参数
        allParam: [],
        //选中的商品分类
        category: [],
        //分类列表
        categoryList: [],
        //级联菜单属性
        casProps: {
          expandTrigger: "hover",
          value: "cat_id",
          label: "cat_name",
        },

        //上传图片配置
        dialogImageUrl: "",
        dialogImageVisible: false,
        //基本信息验证规则
        baseInfoRules: {
          name: [
            { required: true, message: "请输入商品名称", trigger: "blur" },
            {
              min: 1,
              max: 255,
              message: "商品名称长度在 1 到 255 个字符",
              trigger: "blur",
            },
          ],
          price: [
            { validator: checkPrice, trigger: "change" },
            { required: true, message: "请输入商品价格", trigger: "change" },
          ],
          weight: [
            { validator: checkWeight, trigger: "change" },
            { required: true, message: "请输入商品重量", trigger: "change" },
          ],
          num: [
            { validator: checkNum, trigger: "change" },
            { required: true, message: "请输入商品数量", trigger: "change" },
          ],
          category: [
            { validator: checkCategory, trigger: "change" },
            { required: true, message: "请选择商品分类", trigger: "change" },
          ],
        },
      },
      //富文本编辑器配置
      tinymceConfig: {
        setting: {
          toolbar:
            "undo redo bold italic underline strikethrough forecolor backcolor fontselect fontsizeselect   formatselect alignleft aligncenter alignright alignjustify  link unlink  numlist bullist  image media table    indent outdent  superscript subscript  removeformat fullscreen",

          plugins: "link image media table lists fullscreen quickbars",
          language: "zh_CN", //本地化设置
          height: 350,
          branding: false,
          resize: false,
          auto_focus: true,
          toolbar_mode: "wrap",
          elementpath: false,
          statusbar: false,
          menubar: false,
          toolbar_drawer: false,
        },
      },
    };
  },
  methods: {
    getCategoryList() {
      //获取商品分类列表
      //发起请求
      this.$axios
        .get("/categories", {
          params: {
            type: [1, 2, 3],
          },
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //设置分类列表数据
            this.editGoodsInfo.categoryList = res.data;
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    getGoodsInfo() {
      //根据ID查询商品信息
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .get("/goods/" + this.editGoodsId)
        .then((res) => {
          if (res.meta.status == 200) {
            console.log(res.data);
            this.editGoodsInfo.name = res.data.goods_name;
            this.editGoodsInfo.price = res.data.goods_price;
            this.editGoodsInfo.num = res.data.goods_number;
            this.editGoodsInfo.weight = res.data.goods_weight;
            this.editGoodsInfo.content = res.data.goods_introduce;
            this.editGoodsInfo.category = res.data.cat_three_id;
            this.editGoodsInfo.allParam = res.data.attrs;
            //处理图片
            if (res.data.pics.length > 0) {
              res.data.pics.forEach((item) => {
                this.editGoodsInfo.pics.push({
                  name: "goodsImg" + item.pics_id,
                  url: item.pics_big_url,
                });
              });
            }
            console.log(this.$refs["upload"]);
            console.log(res.data.pics);
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //请求失败
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    switchTag(activeName, oldActiveName) {
      var flag = true;
      if (oldActiveName == "baseInfo" && activeName != "baseInfo") {
        this.$refs["baseInfoForm"].validate((valid) => {
          if (!valid) {
            flag = false;
          }
        });
      }
      if (!flag) {
        this.$message.error("请先完善基本信息");
        return false;
      }
      if (this.editGoodsInfo.category.length < 3) {
        this.$message.error("只能选择三级分类");
        return false;
      }
      if (oldActiveName == "baseInfo" && this.queryFlag) {
        this.getParams("many");
        this.getParams("only");
        this.queryFlag = false;
      }
      switch (activeName) {
        case "baseInfo":
          this.setpsActive = 0;
          break;
        case "params":
          this.setpsActive = 1;
          break;
        case "attr":
          this.setpsActive = 2;
          break;
        case "img":
          this.setpsActive = 3;
          break;
        case "content":
          this.setpsActive = 4;
          break;
        default:
          break;
      }
    },
    getParams(type) {
      //根据分类ID查询参数
      var id = this.editGoodsInfo.category;
      //发起请求
      this.$axios
        .get("/categories/" + id + "/attributes", {
          params: {
            sel: type,
          },
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //处理数据
            if (type == "many") {
              var many = this.editGoodsInfo.allParam.filter((item) => {
                return item.attr_sel == "many";
              });

              res.data.forEach((item) => {
                if (item.attr_vals) {
                  item.attr_vals = item.attr_vals.split(",");
                  if (item.attr_vals.length > 0) {
                    item.attr_vals.forEach((item2, index) => {
                      var tempFlag = false;
                      many.forEach((item3) => {
                        if (tempFlag) {
                          return;
                        }
                        if (item3.attr_value) {
                          if (item2 == item3.attr_value) {
                            tempFlag = true;
                            return;
                          }
                        }
                      });
                      if (tempFlag) {
                        item.attr_vals[index] = {
                          value: item2,
                          bool: true,
                        };
                      } else {
                        item.attr_vals[index] = {
                          value: item2,
                          bool: false,
                        };
                      }
                    });
                  }
                }
              });
              this.editGoodsInfo.params = res.data;
            } else if (type == "only") {
              var only = this.editGoodsInfo.allParam.filter((item) => {
                return item.attr_sel == "only";
              });
              res.data.forEach((item) => {
                item.attr_vals = "";
                only.forEach((item2) => {
                  if (item.attr_id == item2.attr_id) {
                    item.attr_vals = item2.attr_value;
                    return;
                  }
                });
              });
              this.editGoodsInfo.attrs = res.data;
            }
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    editGoodsSubmit() {
      //修改商品提交
      this.setpsActive = 5;
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      console.log(this.$refs["upload"]);
      // 获取上传图片组
      var picsArr = [];
      if (this.$refs["upload"].uploadFiles.length > 0) {
        this.$refs["upload"].uploadFiles.forEach((item) => {
          if (item.response) {
            if (item.response.meta.status == 200) {
              picsArr.push({
                pic: item.response.data.tmp_path,
              });
            }
          } else if (item.status == "success") {
            picsArr.push({
              pic: item.url.replace(
                "http://127.0.0.1:8888/uploads/goodspics/big_",
                "tmp_uploads/"
              ),
            });
          }
        });
      }
      //获取动态参数和静态属性
      var attrs = [];
      if (this.editGoodsInfo.attrs.length > 0) {
        this.editGoodsInfo.attrs.forEach((item) => {
          if (item.attr_vals.trim()) {
            attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            });
          }
        });
      }
      if (this.editGoodsInfo.params.length > 0) {
        this.editGoodsInfo.params.forEach((item) => {
          if (item.attr_vals.length > 0) {
            item.attr_vals.forEach((item2) => {
              if (item2.bool) {
                attrs.push({
                  attr_id: item.attr_id,
                  attr_value: item2.value,
                });
              }
            });
          }
        });
      }
      console.log(this.$refs["upload"]);
      //发起请求
      this.$axios
        .put("/goods/" + this.editGoodsId, {
          goods_name: this.editGoodsInfo.name,
          goods_cat: this.$refs["addCatCascader"]
            .getCheckedNodes()[0]
            .path.join(","),
          goods_price: parseFloat(this.editGoodsInfo.price),
          goods_number: parseInt(this.editGoodsInfo.num),
          goods_weight: parseFloat(this.editGoodsInfo.weight),
          goods_introduce: this.editGoodsInfo.content,
          pics: picsArr,
          attrs: attrs,
        })
        .then((res) => {
          if (res.meta.status == 200) {
            this.setpsActive = 6;
            //提示成功信息
            this.$message.success("修改商品成功");
            //跳转路由
            this.$emit("go-route", "/goods");
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //请求失败
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      console.log(this.$refs["upload"]);
    },
    handlePictureCardPreview(file) {
      this.editGoodsInfo.dialogImageUrl = file.url;
      this.editGoodsInfo.dialogImageVisible = true;
    },
  },
  created() {
    this.editGoodsId = parseInt(this.$route.params.id);
    this.getCategoryList();
  },
  mounted() {
    this.getGoodsInfo();
  },
};
</script>

<style lang="less" scoped>
::v-deep .el-card {
  height: auto;
  overflow: auto;
  .el-tabs--left {
    height: auto !important;
  }
}
</style>
<style lang="less">
.edit-goods {
  .el-steps {
    .el-step__title {
      font-size: 12px !important;
    }
  }
}
</style>